package com.hup.minicontroller.client.service;

import com.hup.minicontroller.client.model.AppState;
import com.hup.minicontroller.client.mvp.IConnectedView;
import com.hup.minicontroller.common.model.dto.ControlConfigDto;
import com.hup.minicontroller.common.model.dto.ScreenDataResponse;
import com.hup.utils.commons.start.ApplicationContext;
import com.hup.utils.io.netty.annotation.DataHandlerMethod;
import com.hup.utils.io.netty.handler.DataHandler;
import com.hup.utils.swing.ImageUtil;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 服务端消息处理类,相当于Controller
 *
 * @author hugan
 * @date 2021/5/18
 */
@Component
public class DataHandlerService implements DataHandler {

    private final AppState appState;
    private final ApplicationContext applicationContext;

    public DataHandlerService(AppState appState, ApplicationContext applicationContext) {
        this.appState = appState;
        this.applicationContext = applicationContext;
    }

    @DataHandlerMethod
    public void controlConfigDto(ControlConfigDto controlConfig) {
        appState.getControlConfig().apply(controlConfig);
        applicationContext.executeIfExist(IConnectedView.class, IConnectedView::onControlConfigChanged);
    }

    @DataHandlerMethod
    public void screenDataDto(ScreenDataResponse screenDataResponse) {
        byte[] data = screenDataResponse.getData();
        Image image = new ImageIcon(data).getImage();
        if (image != null) {
            BufferedImage bufferedImage = ImageUtil.getImage(image);
            if (bufferedImage != image) image.flush();
            applicationContext.executeIfExist(IConnectedView.class, i -> i.onScreenData(bufferedImage));
        }
    }
}
